package com.clps.rulesregulations.controller;

import com.clps.rulesregulations.domain.Role;
import com.clps.rulesregulations.domain.User;
import com.clps.rulesregulations.form.UserRoleForm;
import com.clps.rulesregulations.service.RoleService;
import com.clps.rulesregulations.service.UserRoleService;
import com.clps.rulesregulations.service.UserService;
import com.clps.rulesregulations.util.Const;
import com.clps.rulesregulations.util.PasswordHelper;
import com.clps.rulesregulations.util.ResultView;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制层
 *
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;

    /**
     * 跳转到列表页
     *
     * @return
     */
    @RequiresRoles("管理员")
    @GetMapping("/list")
    public String toList() {
        return "user/user";
    }

    /**
     * 分页查询所有用户
     *
     * @param condition
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public ResultView list(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<User> users = userService.findUsersByPage(condition);
        resultView.setValue(users);
        return resultView;
    }

    /**
     * 分页查询所有用户
     *
     * @param condition
     * @return
     */
    @PostMapping("/getCreator")
    @ResponseBody
    public ResultView getCreator(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Session session = SecurityUtils.getSubject().getSession();
        User u = (User)session.getAttribute("userSession");
        String name = u.getName();

        resultView.setValue(name);
        return resultView;
    }

    /**
     * 分页查询所有用户
     *
     * @param condition
     * @return
     */
    @PostMapping("/searchByDeptId")
    @ResponseBody
    public ResultView searchByDeptId(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<User> users = userService.findUsersByDeptId(condition);
        resultView.setValue(users);
        return resultView;
    }

    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public ResultView add(@RequestBody User user) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("请填入必填项");
            return resultView;
        }
        //查询用户名是否已经使用
        User dbUser = userService.findUserByUsername(user.getUsername());
        if (dbUser != null) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("用户名已经存在");
            return resultView;
        }
        user.setEnable(Const.ENABLE_NORMAL);
        userService.addUser(user);
        return resultView;
    }

    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public ResultView update(@RequestBody User user) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getName())) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("请填入必填项");
            return resultView;
        }
        //查询用户名是否已经使用
        User dbUser = userService.checkUser(user.getUsername(),String.valueOf(user.getId()));
        if (dbUser != null) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("用户名已经存在");
            return resultView;
        }
        user.setEnable(Const.ENABLE_NORMAL);
        userService.updateUser(user);
        return resultView;
    }

    /**
     * 查询所有用户
     *
     * @param condition
     * @return
     */
    @PostMapping("/listall")
    @ResponseBody
    public ResultView listall(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        List<User> users = userService.listAll(condition);
        resultView.setValue(users);
        return resultView;
    }

    /**
     * 根据资源ID查询资源内容
     *
     * @param userId
     * @return
     */
    @GetMapping("/edit")
    @ResponseBody
    public ResultView findUser(@RequestParam Integer userId) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        User user = userService.findUserByUserId(userId);
        if (user != null) {
            String fullUrl = user.getFullUrl();
            if (!StringUtils.isEmpty(fullUrl)) {
                String[] arr = fullUrl.split(",");
                Integer[] iarr = new Integer[arr.length];
                for (int i = 0; i < arr.length; i++) {
                    iarr[i] = Integer.valueOf(arr[i]);
                }
                user.setFullUrlArr(iarr);
            }
        }
        resultView.setValue(user);
        return resultView;
    }

    /**
     * 根据用户ID修改密码
     *
     * @param userId
     * @return
     */
    @GetMapping("/changePwd")
    @ResponseBody
    public ResultView changePwd(@RequestParam Integer userId) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        User user = userService.findUserByUserId(userId);
        user.setPassword("123456");
        new PasswordHelper().encryptPassword(user);
        userService.updatePassword(user);
        return resultView;
    }


    /**
     * 根据用户ID查询用户角色
     *
     * @param userId
     * @return
     */
    @GetMapping("/role/edit")
    @ResponseBody
    public ResultView findUserRole(@RequestParam Integer userId) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        //查询所有角色
        List<Role> roles = roleService.findAll();
        //查询角色Ids
        List<Integer> roleIds = userRoleService.findRoleIdsByUserId(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("roles", roles);
        map.put("roleIds", roleIds);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 修改用户角色信息
     *
     * @return
     */
    @PostMapping("/role/edit")
    @ResponseBody
    public ResultView updateUserRole(@RequestBody UserRoleForm userRoleForm) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        userRoleService.updateUserRole(userRoleForm.getUserId(), userRoleForm.getRoleIds());
        return resultView;
    }

    /**
     * 修改密码
     *
     * @param user
     * @return
     */
    @PostMapping("/changepassword")
    @ResponseBody
    public ResultView changepassword(@RequestBody User user) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Session session = SecurityUtils.getSubject().getSession();
        User u = (User)session.getAttribute("userSession");
        user.setUsername(u.getUsername());
        //查询用户名是否已经使用
        User dbUser = userService.findUserByUsername(user.getUsername());
        String password = user.getOldPassword();
        new PasswordHelper().encryptOldPassword(user);

        if (dbUser!=null) {
            if(!user.getOldPassword().equals(dbUser.getPassword())){
                resultView.setStatus(ResultView.ERROR);
                resultView.setMsg("原密码错误！");
                return resultView;
            }
        }
        new PasswordHelper().encryptPassword(user);
        user.setEnable(Const.ENABLE_NORMAL);
        userService.updatePassword(user);
        return resultView;
    }

    /**
     * 锁定用户账号
     *
     * @param userId
     * @return
     */
    @GetMapping("/lock")
    @ResponseBody
    public ResultView lockUser(@RequestParam Integer userId) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        userService.lockUser(userId);
        return resultView;
    }

    /**
     * 锁定用户账号
     *
     * @param userId
     * @return
     */
    @GetMapping("/recoveryUser")
    @ResponseBody
    public ResultView recoveryUser(@RequestParam Integer userId) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        userService.recoveryUser(userId);
        return resultView;
    }
}